import logging
import json
import yaml
import requests


def add_service(env, project_name, host, port, weight):
    with open('data/config/token.yml', 'r') as f:
        config = yaml.safe_load(f)
    with open('data/config/config.yaml', 'r') as f2:
        config_data = yaml.safe_load(f2)
    with open('data/config/project_id.txt', 'r') as f3:
        project_id = f3.read().strip()
    with open('data/config/deploy_id.txt', 'r') as f4:
        deploy_id = f4.read().strip()

    url = config_data['environments'][env]['host'] + config_data['environments'][env]['add_service']
    token = config['token']
    protocol = config_data['environments'][env]['protocol']
    headers = {'Content-Type': 'application/json', 'version': '2.0', 'Authorization': token, 'Tenantid': project_id}
    query_params = {
    }
    payload = {
        "name": project_name,
        "project": project_id,
        "registerName": "Mock",
        "protocol": protocol,
        "spaceTargets": [{
            "deploySpaceId": deploy_id,
            "targets": [{
                "host": host,
                "port": port,
                "weight": weight
            }]
        }]
    }
    data = json.dumps(payload)
    try:
        # 发送 POST 请求
        response = requests.post(url, data=data, headers=headers, params=query_params)
        # 检查响应状态
        response.raise_for_status()  # 如果响应状态码不是 200，抛出异常
        parsed_data = response.json()
        logging.info("成功----接口有响应，响应数据：%s", json.dumps(parsed_data, ensure_ascii=False))
    except requests.exceptions.RequestException as e:
        logging.error("请求失败: %s", str(e))
    except json.JSONDecodeError:
        logging.error("解析 JSON 响应失败")
